import time
import jwt

from lab.settings import JWT_TOKEN_EXPIRE_TIME, JWT_SECRET_KEY, JWT_ALGORITHM, JWT_REFRESH_SECRET_KEY, \
    JWT_REFRESH_TOKEN_EXPIRE_TIME


class JwtUtils:

    @staticmethod
    def generate_jwt_token(user_id, user_name) -> str:
        """根据用户id生成token"""
        payload = {'user_id': user_id, 'user_name': user_name, 'exp': int(time.time()) + JWT_TOKEN_EXPIRE_TIME}
        return jwt.encode(payload, JWT_SECRET_KEY, algorithm=JWT_ALGORITHM)

    @staticmethod
    def generate_jwt_refresh_token(user_id, user_name) -> str:
        """根据用户id生成token"""
        payload = {'user_id': user_id, 'user_name': user_name, 'exp': int(time.time()) + JWT_REFRESH_TOKEN_EXPIRE_TIME}
        return jwt.encode(payload, JWT_REFRESH_SECRET_KEY, algorithm=JWT_ALGORITHM)

    @staticmethod
    def verify_jwt_token(token) -> bool:
        """验证用户token"""
        try:
            payload = jwt.decode(token, JWT_SECRET_KEY, algorithms=[JWT_ALGORITHM])
        except jwt.PyJWTError:
            print('token解析失败')
            return False
        else:
            print(payload)
            exp = int(payload.pop('exp'))
            if time.time() > exp:
                print('已失效')
                return False
            return True